package com.myslef.teaching_platfrom.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.myslef.teaching_platfrom.common.R;
import com.myslef.teaching_platfrom.domain.talk.Talk;
import com.myslef.teaching_platfrom.domain.talk.TalkList;
import com.myslef.teaching_platfrom.domain.users.User;
import com.myslef.teaching_platfrom.service.TalkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/talk")
@CrossOrigin(origins = "http://localhost:8080")
public class TalkController {

    @Autowired
    private TalkService talkService;

    @Value("${upload.dir}") // 读取配置文件中的上传文件保存目录
    private String uploadDir;

    @GetMapping
    public R<List> getTalkList(HttpServletRequest request){
        String id = request.getParameter("id");

        //1、根据课堂id将课堂中的评论全部提取出来
        LambdaQueryChainWrapper<Talk> lqcw = talkService.lambdaQuery();
//        lqcw.select(Talk::getId, Talk::getUserId, Talk::getClassId, Talk::getBeforeId, Talk::getFatherId, Talk::getLevel,
//                Talk::getAnonymity, Talk::getCreate_time, Talk::getComments, User.)


        LambdaQueryWrapper<Talk> lqw = new LambdaQueryWrapper<>();
        List<Talk> list = talkService.getCommentsWithUsers(id);
        System.out.println(list);
        List<TalkList> res = new ArrayList<>();

        //将第一层全部加入
        list.forEach(item ->{if(item.getLevel() == 1) res.add(new TalkList(item));});
        //将第二层依次加入对应的对话中
        for (TalkList items : res) {
            list.forEach(item -> {
                if (item.getLevel() == 2 && item.getFatherId() == items.getTalk().getId())
                    items.add(item);
            });
        }
        System.out.println(res);
        R r = new R();
        r.addAll(res);
        return r;
    }

    @PostMapping
    public R submit(@RequestBody Map<String, Object> data) {
        String contentValue = (String) data.get("contentValue");
        Map<String, Object> userMap = (Map<String, Object>) data.get("user");

        Integer userId = (Integer)userMap.get("id");
        Integer classId = Integer.parseInt((String)data.get("classId"));
        Integer beforeTalkId = ((Integer)data.get("beforeTalkId"));
        Integer beforeUserId = (Integer) data.get("beforeUserId");
        Short anonymity = ((Boolean) data.get("anonymity")).booleanValue() ? (short) 1 : (short) 0;;
        Integer fatherId = (Integer)data.get("fatherId");
        Integer level = (Integer) data.get("level");
        Talk talk = new Talk();


        talk.setUserId(userId);
//        talk.setPicUrl("https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png");
        talk.setClassId(classId);
        talk.setBeforeUserId(beforeUserId);
        talk.setBeforeTalkId(beforeTalkId);
        talk.setFatherId(fatherId);
        talk.setLevel(level);
        talk.setContent(contentValue);
        talk.setAnonymity(anonymity);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        talk.setCreateTime(timestamp);


        talkService.save(talk);
        return R.success(talk);
    }

    @PostMapping("/{id}")
    public R submitContent(@RequestBody Map<String, Object> data) {
        String contentValue = (String) data.get("contentValue");
        Map<String, Object> userMap = (Map<String, Object>) data.get("user");

        Integer userId = (Integer)userMap.get("id");
        String url = (String)userMap.get("picUrl");
        Integer classId = Integer.parseInt((String)data.get("classId"));
        Short anonymity = ((Boolean) data.get("anonymity")).booleanValue() ? (short) 1 : (short) 0;
        Integer level = (Integer) data.get("level");

        Talk talk = new Talk();

        talk.setUserId(userId);
        talk.setClassId(classId);
        talk.setLevel(level);
        talk.setContent(contentValue);
        talk.setAnonymity(anonymity);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        talk.setCreateTime(timestamp);
        talkService.save(talk);
        return R.success(talk);
    }


    @PostMapping("/talk2")
    public R createComment(@RequestParam(required = false,value = "file") MultipartFile[] files,
                           @RequestParam(required = false,value = "content") String content,
                           @RequestParam(required = false,value = "beforeTalkId") String beforeTalkId,
                           @RequestParam(required = false,value = "beforeUserId") String beforeUserId,
                           @RequestParam(required = false,value = "fatherId") String fatherId,
                           @RequestParam("user")String strUser,
                           @RequestParam("anonymity")String anonymity,
                           @RequestParam("classId")String classId,
                           @RequestParam("level")String level) throws IOException {
        if(files == null && content == null){
            return R.error("请输入内容");
        }
        // 创建上传目录
        User user = JSON.parseObject(strUser, User.class);
        Path uploadPath = Paths.get(uploadDir+"/comment/"+System.currentTimeMillis()+user.getId());
        List<String> list = new ArrayList<>();
        if(files != null)
        for (int i = 0; i < files.length; i++) {
            String originalFileName = files[i].getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
            String newFileName =i +"."+ fileExtension;
            if (!Files.exists(uploadPath)) {
                try {
                    Files.createDirectories(uploadPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Path filePath = Paths.get(uploadPath.toString(), newFileName);
            list.add(filePath.toString());
            Files.write(filePath, files[i].getBytes());
        }
//        System.out.println(user);
        Talk talk = new Talk();
        String str = String.join(",", list);
        talk.setImgUrlList(str);
        talk.setUserId(user.getId());
        talk.setClassId(Integer.parseInt(classId));
        talk.setLevel(Integer.parseInt(level));
        talk.setContent(content);
        if(beforeTalkId!=null)
        talk.setBeforeTalkId(Integer.valueOf(beforeTalkId));
        if(beforeUserId!=null)
        talk.setBeforeUserId(Integer.valueOf(beforeUserId));
        if(fatherId!=null)
        talk.setFatherId(Integer.valueOf(fatherId));
        if(anonymity.equals("false"))
            talk.setAnonymity((short)0);
        else
            talk.setAnonymity((short) 1);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        talk.setCreateTime(timestamp);
        talkService.save(talk);
        return R.success(talk);
    }

    @GetMapping("/image/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable Integer id) throws IOException {
        // 从数据库中获取图片路径
        String url = talkService.getListPicUrl(id);
        System.out.println(url);
        // 读取图片文件到内存中
        File file = new File(url);
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        inputStream.close();
        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        // 返回图片内容给前端
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @PostMapping("/onSearch")
    public R onSearch(@RequestBody Map map){
        System.out.println(map);
        String text =map.get("text").toString();
        String classId = map.get("classId").toString();
        List<Talk> list = talkService.getSearchList(text, classId);
        return R.success(list);
    }

}
